/**
 * Copyright 2009-2020 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

/**
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XMLConfigBuilder extends BaseBuilder {

    /** 配置文件是否已经被加载 */
    private boolean parsed;
    /** Xml文件解析器 */
    private final XPathParser parser;
    /** 当前运行环境 只能有一个 */
    private String environment;
    /** 反射工厂 */
    private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

    public XMLConfigBuilder(Reader reader) {
        this(reader, null, null);
    }

    public XMLConfigBuilder(Reader reader, String environment) {
        this(reader, environment, null);
    }

    public XMLConfigBuilder(Reader reader, String environment, Properties props) {
        this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
    }

    public XMLConfigBuilder(InputStream inputStream) {
        this(inputStream, null, null);
    }

    public XMLConfigBuilder(InputStream inputStream, String environment) {
        this(inputStream, environment, null);
    }

    public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
        // new XPathParser(reader, true, props, new XMLMapperEntityResolver())就是创建XpathParser的过程。
        this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
    }

    private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
        super(new Configuration());
        ErrorContext.instance().resource("SQL Mapper Configuration");
        this.configuration.setVariables(props);
        this.parsed = false;
        this.environment = environment;
        this.parser = parser;
    }

    public Configuration parse() {
        // 如果解析过，就抛异常，保证只解析一次
        if (parsed) {
            throw new BuilderException("Each XMLConfigBuilder can only be used once.");
        }
        parsed = true;
        // 解析mybatis-config.xml配置文件，从根节点/configuration开始解析，解析封装成Configuration对象
        // 并返回这个configuration对象返回
        parseConfiguration(parser.evalNode("/configuration"));
        return configuration;
    }

    private void parseConfiguration(XNode root) {
        try {
            // issue #117 read properties first
            // properties节点，用来读取properties配置文件
            propertiesElement(root.evalNode("properties"));
            // settings节点 这里只是读取 真正去解析在下面
            Properties settings = settingsAsProperties(root.evalNode("settings"));
            // 加载settings节点中的vfs相关配置信息
            loadCustomVfs(settings);
            // 加载settings节点中的logImpl相关配置信息【日志配置】
            loadCustomLogImpl(settings);
            // typeAliases别名配置
            typeAliasesElement(root.evalNode("typeAliases"));
            // plugins插件配置
            pluginElement(root.evalNode("plugins"));
            // 对象工厂，可以自定义，已有默认实现
            objectFactoryElement(root.evalNode("objectFactory"));
            // 对象包装工厂
            objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
            // 反射工厂
            reflectorFactoryElement(root.evalNode("reflectorFactory"));
            // 拿settings解析的属性，给configuration对象赋值
            settingsElement(settings);
            // read it after objectFactory and objectWrapperFactory issue #631
            // environments环境配置读取
            environmentsElement(root.evalNode("environments"));
            // databaseIdProvider数据库配置
            databaseIdProviderElement(root.evalNode("databaseIdProvider"));
            // typeHandlers类型处理器处理，在这里，mybatis已经把基本的都封装好了，我们可以往里面替换
            typeHandlerElement(root.evalNode("typeHandlers"));
            // 重点，这里是解析mapper映射的，所有的sql之类的都会在这里进行解析
            mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
            throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
    }

    private Properties settingsAsProperties(XNode context) {
        if (context == null) {
            return new Properties();
        }
        Properties props = context.getChildrenAsProperties();
        // Check that all settings are known to the configuration class
        MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
        // 获得了所有的prop之后，遍历，看看是不是可以配置的，如果不存在于Configuration配置中【没有setter方法】，就抛异常
        for (Object key : props.keySet()) {
            if (!metaConfig.hasSetter(String.valueOf(key))) {
                throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
            }
        }
        return props;
    }

    private void loadCustomVfs(Properties props) throws ClassNotFoundException {
        String value = props.getProperty("vfsImpl");
        if (value != null) {
            String[] clazzes = value.split(",");
            for (String clazz : clazzes) {
                if (!clazz.isEmpty()) {
                    @SuppressWarnings("unchecked")
                    Class<? extends VFS> vfsImpl = (Class<? extends VFS>) Resources.classForName(clazz);
                    configuration.setVfsImpl(vfsImpl);
                }
            }
        }
    }

    private void loadCustomLogImpl(Properties props) {
        Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
        configuration.setLogImpl(logImpl);
    }

    private void typeAliasesElement(XNode parent) {
        // 判断是否存在typeAliases标签
        if (parent != null) {
            // 解析每一个 别名
            for (XNode child : parent.getChildren()) {
                if ("package".equals(child.getName())) {
                    // 先扫描包的
                    String typeAliasPackage = child.getStringAttribute("name");
                    // 拿configuration里面的typeAliasRegistry 这里其实已经有了默认注册进去的别名，在new Configuration的时候 实例化了TypeAliasRegistry
                    configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
                } else {
                    // 如果不是package类型的，就直接读取子节点的 alias别名 以及type类全限定名 来注册
                    String alias = child.getStringAttribute("alias");
                    String type = child.getStringAttribute("type");
                    try {
                        // 类加载 获取Class 如果没有会抛异常的
                        Class<?> clazz = Resources.classForName(type);
                        if (alias == null) {
                            // 如果没有写别名 则默认规则
                            typeAliasRegistry.registerAlias(clazz);
                        } else {
                            // 有别名就用别名咯
                            typeAliasRegistry.registerAlias(alias, clazz);
                        }
                    } catch (ClassNotFoundException e) {
                        throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
                    }
                }
            }
        }
    }

    private void pluginElement(XNode parent) throws Exception {
        if (parent != null) {
            // 遍历插件 其实是拦截器 可以拦截Executor ParameterHandler ResultSetHandler StatementHandler的部分方法
            // Executor：执行sql语句的地方
            // ParameterHandler: 参数处理
            // ResultSetHandler: 结果集处理
            for (XNode child : parent.getChildren()) {
                // 获取<plugin>标签的interceptor属性
                // 如果需要自定义一个插件，要继承Interceptor接口
                String interceptor = child.getStringAttribute("interceptor");
                // 获取拦截器的属性信息，转为Properties对象
                Properties properties = child.getChildrenAsProperties();
                // 创建拦截器实例
                Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
                // 设置拦截器实例属性信息
                interceptorInstance.setProperties(properties);
                // 将拦截器实例添加到拦截器链中
                configuration.addInterceptor(interceptorInstance);
            }
        }
    }

    /**
     * 顾名思义就是对象工厂 mybatis已经有默认实现 也就是默认的构造方法 有参数就有参构造方法来实例化 一般也不需要配置 如果需要 去继承DefaultObjectFactory类或实现ObjectFactory接口即可
     *
     * @param context
     *
     * @throws Exception
     */
    private void objectFactoryElement(XNode context) throws Exception {
        if (context != null) {
            // 获取objectFactory标签的type属性
            String type = context.getStringAttribute("type");
            // 获取属性
            Properties properties = context.getChildrenAsProperties();
            // 无参构造方法
            ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            // 设置属性进去 其实默认的没啥用 如果要自定义可能会用上
            factory.setProperties(properties);
            // 丢进configuration对象里
            configuration.setObjectFactory(factory);
        }
    }

    private void objectWrapperFactoryElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            configuration.setObjectWrapperFactory(factory);
        }
    }

    private void reflectorFactoryElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            configuration.setReflectorFactory(factory);
        }
    }

    /**
     * 解析properties标签
     *
     * @param context
     *
     * @throws Exception
     */
    private void propertiesElement(XNode context) throws Exception {
        if (context != null) {
            // 先解析是否有子标签，读取里面的name和value属性并放入到Properties对象中
            Properties defaults = context.getChildrenAsProperties();
            // resource属性
            String resource = context.getStringAttribute("resource");
            // url属性
            String url = context.getStringAttribute("url");
            if (resource != null && url != null) {
                // resource和url只能配置其中之一，两者不可以共存，否则不知道哪个该优先
                throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
            }
            if (resource != null) {
                // resource，则解析资源路径的配置到Properties中
                defaults.putAll(Resources.getResourceAsProperties(resource));
            } else if (url != null) {
                // url，则去网络请求，然后读取配置到Properties中
                defaults.putAll(Resources.getUrlAsProperties(url));
            }
            // 首先获取configuration中现有的variables[也是Properties类型]
            Properties vars = configuration.getVariables();
            if (vars != null) {
                // 如果variables不为空，则填充到Properties对象中
                defaults.putAll(vars);
            }
            // 然后把Properties配置信息塞入到XPathParser中
            parser.setVariables(defaults);
            // 再把Properties配置信息塞入到Configuration的variables中
            configuration.setVariables(defaults);
            // 从这里可以看出，优先级从低到高是： 子标签 -> resource/url -> configuration.variables【这里是new XMLConfigBuilder的时候可以传入的】 ，且最终结果是把Properties塞到了XPathParser以及Configuration中
        }
    }

    private void settingsElement(Properties props) {
        configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
        configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
        configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
        configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
        configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
        configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
        configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
        configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
        configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
        configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
        configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
        configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
        configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
        configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
        configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
        configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
        configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
        configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
        configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
        configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
        configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
        configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
        configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
        configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
        configuration.setLogPrefix(props.getProperty("logPrefix"));
        configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
        configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
        configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
    }

    private void environmentsElement(XNode context) throws Exception {
        if (context != null) {
            // 默认环境就是default，如果不指定的话
            if (environment == null) {
                environment = context.getStringAttribute("default");
            }
            // 遍历每个env环境
            for (XNode child : context.getChildren()) {
                // 获取id
                String id = child.getStringAttribute("id");
                // 如果id匹配上了上面的environment 则加载这个环境的配置
                if (isSpecifiedEnvironment(id)) {
                    // 获取事务工厂 MyBatis有两种，JDBC和MANAGED
                    // JDBC：使用JDBC的事务
                    // MANAGED：事务委托给容器
                    TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
                    // 数据源配置
                    DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
                    DataSource dataSource = dsFactory.getDataSource();
                    // 构建Environment对象 需要事务已经数据源
                    Environment.Builder environmentBuilder = new Environment.Builder(id)
                            .transactionFactory(txFactory)
                            .dataSource(dataSource);
                    // 把Environment对象塞进Configuration中
                    // 1、configuration --> Environment ---> DataSource ---> 。。。。。
                    // 2、配置文件和实体类的定义层次结构是一致的，
                    // todo 1 / 2 ===》 Configuration类对应的就是我们的 mybatis-config.xml 配置文件，
                    //             我们配置的信息经过解析后就会存储到Configuration的成员变量中。
                    configuration.setEnvironment(environmentBuilder.build());
                }
            }
        }
    }

    private void databaseIdProviderElement(XNode context) throws Exception {
        DatabaseIdProvider databaseIdProvider = null;
        if (context != null) {
            String type = context.getStringAttribute("type");
            // awful patch to keep backward compatibility
            if ("VENDOR".equals(type)) {
                type = "DB_VENDOR";
            }
            Properties properties = context.getChildrenAsProperties();
            databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
            databaseIdProvider.setProperties(properties);
        }
        Environment environment = configuration.getEnvironment();
        if (environment != null && databaseIdProvider != null) {
            String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
            configuration.setDatabaseId(databaseId);
        }
    }

    private TransactionFactory transactionManagerElement(XNode context) throws Exception {
        if (context != null) {
            // 读取事务类型
            String type = context.getStringAttribute("type");
            // 读取配置
            Properties props = context.getChildrenAsProperties();
            // 实例化事务工厂   去resolveClass：从别名列表里拿
            TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            // 塞配置到事务工厂中去
            factory.setProperties(props);
            return factory;
        }
        // 没有读取到事务配置就抛异常咯
        throw new BuilderException("Environment declaration requires a TransactionFactory.");
    }

    private DataSourceFactory dataSourceElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            Properties props = context.getChildrenAsProperties();
            DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            factory.setProperties(props);
            return factory;
        }
        throw new BuilderException("Environment declaration requires a DataSourceFactory.");
    }

    private void typeHandlerElement(XNode parent) {
        if (parent != null) {
            for (XNode child : parent.getChildren()) {
                if ("package".equals(child.getName())) {
                    // 跟别名类似，有包扫描注册或者单个类注册
                    String typeHandlerPackage = child.getStringAttribute("name");
                    typeHandlerRegistry.register(typeHandlerPackage);
                } else {
                    String javaTypeName = child.getStringAttribute("javaType");
                    String jdbcTypeName = child.getStringAttribute("jdbcType");
                    String handlerTypeName = child.getStringAttribute("handler");
                    Class<?> javaTypeClass = resolveClass(javaTypeName);
                    JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
                    Class<?> typeHandlerClass = resolveClass(handlerTypeName);
                    if (javaTypeClass != null) {
                        if (jdbcType == null) {
                            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
                        } else {
                            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
                        }
                    } else {
                        typeHandlerRegistry.register(typeHandlerClass);
                    }
                }
            }
        }
    }

    private void mapperElement(XNode parent) throws Exception {
        // <mapper>标签中，可以定义四种获取mapper的方式：
        // 1/ package
        // 2/ resource
        // 3/ url
        // 4/ class
        if (parent != null) {
            for (XNode child : parent.getChildren()) {
                // package的优先级最高
                if ("package".equals(child.getName())) {
                    // 首先还是包扫描
                    String mapperPackage = child.getStringAttribute("name");
                    // 添加到configuration里面去 发现没有mapper注册对象了？直接调用了configuration来注册 但是其实看XMLConfigBuilder的构造方法就知道了 其实这些注册器的引用都来自Configuration
                    configuration.addMappers(mapperPackage);
                } else {
                    String resource = child.getStringAttribute("resource");
                    String url = child.getStringAttribute("url");
                    String mapperClass = child.getStringAttribute("class");
                    if (resource != null && url == null && mapperClass == null) {
                        // resource属性扫描xml
                        ErrorContext.instance().resource(resource);
                        InputStream inputStream = Resources.getResourceAsStream(resource);
                        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                        // 解析xxxMapper.xml配置文件
                        mapperParser.parse();
                    } else if (resource == null && url != null && mapperClass == null) {
                        // url属性扫描
                        ErrorContext.instance().resource(url);
                        InputStream inputStream = Resources.getUrlAsStream(url);
                        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                        mapperParser.parse();
                    } else if (resource == null && url == null && mapperClass != null) {
                        // 通过class属性扫描
                        Class<?> mapperInterface = Resources.classForName(mapperClass);
                        configuration.addMapper(mapperInterface);
                    } else {
                        throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
                    }
                }
            }
        }
    }

    private boolean isSpecifiedEnvironment(String id) {
        if (environment == null) {
            throw new BuilderException("No environment specified.");
        } else if (id == null) {
            throw new BuilderException("Environment requires an id attribute.");
        } else if (environment.equals(id)) {
            return true;
        }
        return false;
    }

}
